package com.gof.example.flyweight;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Created by zhiyuan on 2018/5/8 09:27.
 * haiming.fei@tongdun.cn
 */
public class SimpleResourceFactory {

    private static SimpleResourceFactory factory = new SimpleResourceFactory();

    private ConcurrentHashMap<String, AbstractResource> maps = new ConcurrentHashMap<String, AbstractResource>();

    private SimpleResourceFactory() {
        AbstractResource img, flash, video;

        img = new ImageResource("image");
        maps.put(img.getSourceName(), img);

        flash = new FlashResource("flash");
        maps.put(flash.getSourceName(), flash);

        video = new VideoResource("video");
        maps.put(video.getSourceName(), video);
    }


    public static SimpleResourceFactory instance() {
        return factory;
    }

    public AbstractResource getResource(String key) {
        AbstractResource abstractResource = maps.get(key);
        if (abstractResource == null) {
            //默认是doc
            abstractResource = maps.get("doc");
            if (abstractResource == null) {
                abstractResource = new DefaultResource("doc");
                maps.put(abstractResource.getSourceName(), abstractResource);
            }
        }

        return abstractResource;
    }
}
